Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
Me estoy poniendo "indefinido" al agregar caracteres en mi matriz en javascript

Aquí está mi código, ¿alguien puede explicar por qué me estoy volviendo indefinido? Dividí las palabras y luego las invertí y después de invertir intenté almacenarlas en una matriz diferente. Gracias

 const text = document.querySelector("#text"); const reverseText = document.querySelector("#reverseText"); let words = text.innerHTML.split("").reverse(); console.log(words); let reversedWords = []; let counter = 0; for (var i = 0; i <= words.length - 1; i++) { if (words[i] != " ") { reversedWords[counter] += words[i]; } else { counter++; } } console.log(reversedWords);
 <p id="text">hello nixit</p> <p id="reverseText"></p>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Su problema es que la primera vez que intenta acceder a reversedWords[counter] , no está undefined porque ha inicializado reversedWords para que sea una matriz vacía.

Sin cambiar gran parte de su código (porque dijo que lo está haciendo de esta manera como un desafío ), podría intentar inicializar palabras reversedWords para tener la cantidad adecuada de elementos, inicializados en cadenas vacías

 const content = text.textContent; const words = content.split("").reverse(); const reversedWords = Array.from({ length: content.split(" ").length }, () => "");
about 4 years ago · Juan Pablo Isaza Report

0

Está utilizando una matriz, por lo que necesita push cosas en ella y luego join en una nueva cadena una vez que finaliza la iteración.

 const text = document.querySelector('#text'); const reverseText = document.querySelector('#reverseText'); function reverse(str) { // `split` the string on the spaces const words = str.split(' '); const reversedWords = []; for (let i = 0; i < words.length; i++) { // For each word split, reverse, and then rejoin it const word = words[i].split('').reverse().join(''); // And then add the word to the array reversedWords.unshift(word); } // Return the completed array return reversedWords; } const str = text.textContent; reverseText.textContent = JSON.stringify(reverse(str));
 <p id="text">hello nixit</p> <p id="reverseText"></p>

Documentación adicional

  • unshift
about 4 years ago · Juan Pablo Isaza Report

0

Sugiero usar una cadena en lugar de una matriz. Luego puede dividirlo para convertirlo en una matriz.

 const reversedChars = 'hello nixit'.split("").reverse() const reversedWords = '' reversedChars.forEach(char => { reversedWords += char }) const reversedWordsArray = reversedWords.split(' ') console.log(reversedWords) // Output: tixin olleh console.log(reversedWordsArray) // Output: [ 'tixin', 'olleh' ]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!